package com.netty.server;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class NIOServer {
    public static void main(String[] args) throws IOException {

        //创建一个ServerSocketChannel类似于网络编程中的ServerSocket
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        //得到一个selector对象
        Selector selector = Selector.open();
        //绑定一个端口6666 在服务端进行监听该端口
        serverSocketChannel.socket().bind(new InetSocketAddress(6666));
        //设置非阻塞模式
        serverSocketChannel.configureBlocking(false);

        //把serverSocketChannel注册到selector 事件为OP_ACCEPT
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        //循环等到客户端连接
        while (true){
            if (selector.select(1000) == 0){
                System.out.println("服务器等待了1秒---无连接");
                continue;
            }
            //如果返回的 > 0 就获取到相关的selecttionKey的集合
            //1、如果返回的 > 0 就表示已经获得关注的事件了
            //2.selector.selectedKeys() 返回关注事件的集合
            //通过selectedKeys反向获取通道
            Set<SelectionKey> selectionKeySets = selector.selectedKeys();

            //遍历Set<SelectionKey> 迭代器
            Iterator<SelectionKey> iterator = selectionKeySets.iterator();
            while (iterator.hasNext()){
                //获得到SelectorKey
                SelectionKey key = iterator.next();
                //根据key 对应的通道发送的事件进行相应的处理
                if (key.isAcceptable()){
                    //如果选择器是连接 就生成一个socketChannel来接
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    socketChannel.configureBlocking(false);
                    System.out.println("客户端连接成功-----生成一个socketChannel"+socketChannel.hashCode());
                    //将 socketChannel 注册到selector 关注事件为OP_READ
                    //关联一个buffer
                    socketChannel.register(selector,SelectionKey.OP_READ, ByteBuffer.allocate(1024));

                }
                if (key.isReadable()){
                    //发生读操作的时候
                    SocketChannel channel = (SocketChannel) key.channel();
                    ByteBuffer buffer = (ByteBuffer) key.attachment();
                    channel.read(buffer);
                    System.out.println("from 客户端"+new String(buffer.array()));

                }
                iterator.remove();
            }

        }

    }
}
